from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import random
import time


def click_monitoring_menu(driver, timeout=5):
    """
    判断并点击"运维监控"菜单
    """
    try:
        menu = WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.XPATH, "//*[text()='运维监控']"))
        )
        menu.click()
        print("已点击运维监控菜单")
        return True
    except Exception:
        print("未找到运维监控菜单")
        return False


def click_host_group_menu(driver, timeout=5):
    """
    判断并点击"对象群组"菜单
    """
    try:
        menu = WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.XPATH, "//*[text()='对象群组']"))
        )
        menu.click()
        print("已点击对象群组菜单")
        return True
    except Exception:
        print("未找到对象群组菜单")
        return False


def search_and_reset_by_group_names(driver, wait_time=3, random_count=(2, 3)):
    """
    1. 获取表格中群组列所有内容
    2. 依次填入群组名称输入框，点击搜索，等待，点击重置
    3. 随机选择2-3个群组名重复上述操作（若群组名不足则跳过）
    """
    # 1. 获取所有群组列内容（更精确的XPath）
    try:
        group_name_elements = driver.find_elements(By.XPATH, '//td[contains(@class, "el-table_1_column_2")]//a')
        group_names = [el.text.strip() for el in group_name_elements if el.text.strip()]
        print(f"采集到的群组名: {group_names}")
    except Exception as e:
        print(f"获取群组列失败: {e}")
        return
    if not group_names:
        print("未获取到任何群组名")
        return

    # 2. 依次填入群组名并操作（每次循环都重新查找元素，防止stale element）
    # for name in group_names:
    #     try:
    #         input_box = driver.find_element(By.XPATH, '//label[contains(text(), "群组名称")]/following-sibling::div//input')
    #         search_btn = driver.find_element(By.XPATH, '//span[contains(text(), "搜索")]/ancestor::button')
    #         reset_btn = driver.find_element(By.XPATH, '//span[contains(text(), "重置")]/ancestor::button')
    #         input_box.clear()
    #         input_box.send_keys(name)
    #         search_btn.click()
    #         print(f"已搜索: {name}")
    #         time.sleep(wait_time)
    #         reset_btn = driver.find_element(By.XPATH, '//span[contains(text(), "重置")]/ancestor::button')
    #         reset_btn.click()
    #         print("已重置")
    #         time.sleep(1)
    #     except Exception as e:
    #         print(f"操作群组名 {name} 时出错: {e}")

    # 3. 随机选择2-3个群组名再操作（严格次数，数量不足则跳过）
    min_count = random_count[0]
    max_count = random_count[1]
    if len(group_names) < min_count:
        print(f"群组名数量不足{min_count}，跳过随机操作")
        return
    count = random.randint(min_count, min(max_count, len(group_names)))
    random_names = random.sample(group_names, count)
    print(f"随机选择群组名: {random_names}")
    # 只对前3个群组名执行
    max_query = 3
    for name in group_names[:max_query]:
        try:
            input_box = driver.find_element(By.XPATH,
                                            '//label[contains(text(), "群组名称")]/following-sibling::div//input')
            search_btn = driver.find_element(By.XPATH, '//span[contains(text(), "搜索")]/ancestor::button')
            reset_btn = driver.find_element(By.XPATH, '//span[contains(text(), "重置")]/ancestor::button')
            input_box.clear()
            input_box.send_keys(name)
            search_btn.click()
            print(f"已搜索: {name}")
            time.sleep(wait_time)
            reset_btn = driver.find_element(By.XPATH, '//span[contains(text(), "重置")]/ancestor::button')
            reset_btn.click()
            print("已重置")
            time.sleep(1)
        except Exception as e:
            print(f"操作群组名 {name} 时出错: {e}")